import 'dart:typed_data';

import 'package:bluetooth_protocols_plugin/src/tools/bit_utils.dart';

// 记录生成日期
class RecordDate {
  int year = 0; // 2020-2084
  int month = 0; // 1-12
  int day = 0; // 1-31
  int hour = 0; // 0-23
  int minute = 0; // 0-59
  int second = 0; // 0-59

  int minLength = 4;

  // 从字节数据解析
  RecordDate.fromBytes(Uint8List bytes) {
    if (bytes.length < minLength) {
      throw ArgumentError(
          '字节数组长度不足，无法解析 $runtimeType，期望长度至少为 $minLength，实际长度为 ${bytes.length}');
    }

    var byteData = ByteData.sublistView(bytes);
    int dateValue = byteData.getUint32(0, Endian.little);

    year = BitUtils.getBits(dateValue, 0, 6) + 2020; // 6 bits
    month = BitUtils.getBits(dateValue, 6, 4); // 4 bits
    day = BitUtils.getBits(dateValue, 10, 5); // 5 bits
    hour = BitUtils.getBits(dateValue, 15, 5); // 5 bits
    minute = BitUtils.getBits(dateValue, 20, 6); // 6 bits
    second = BitUtils.getBits(dateValue, 26, 6); // 6 bits
  }

  Uint8List toBytes() {
    var byteData = ByteData(minLength);
    int val = 0;
    val = BitUtils.setBits(val, 0, 5, year - 2020); // 6 bits
    val = BitUtils.setBits(val, 6, 9, month); // 4 bits
    val = BitUtils.setBits(val, 10, 14, day); // 5 bits
    val = BitUtils.setBits(val, 15, 19, hour); // 5 bits
    val = BitUtils.setBits(val, 20, 25, minute); // 6 bits
    val = BitUtils.setBits(val, 26, 31, second); // 6 bits
    byteData.setInt32(0, val, Endian.little);
    return byteData.buffer.asUint8List();
  }

  Map<String, dynamic> toMap() {
    return {
      'year': year,
      'month': month,
      'day': day,
      'hour': hour,
      'minute': minute,
      'second': second,
    };
  }

  DateTime toDateTime() {
    return DateTime(year, month, day, hour, minute, second);
  }
}
